package com.xuetang9.fujian.threaddemo;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.nio.CharBuffer;
import java.util.Scanner;

/**
 * @author: fujian
 * @description: 管道流：主要用于线程之间的通信，传输的媒介是内存
 * 1、字节流：PipedInputStream,PipedOutputStream
 * 2、字符流：PipedRead PipedWriter
 * @date: 2021/5/9 10:05
 * @version: V1.0
 * @package: com.xuetang9.fujian.threaddemo
 **/
@SuppressWarnings("all")
public class PipedDemo {
    public static void main(String[] args) throws IOException {
        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader();
        writer.connect(reader);
        new Thread(new SendTask(writer)).start();
        new Thread(new PrintTask(reader)).start();
    }
    static class SendTask implements Runnable{
        private PipedWriter writer;

        public SendTask(PipedWriter writer) {
            this.writer = writer;
        }

        @Override
        public void run() {
            Scanner scanner = new Scanner(System.in);
            while (true){
                System.out.println("请输入要发送的字符串");
                String message = scanner.next();
                try {
                    writer.write(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if ("退出".equals(message)){
                    break;
                }
            }
            System.out.println("写入线程结束");
        }
    }
    static class PrintTask implements Runnable{
        private PipedReader reader;

        public PrintTask(PipedReader reader) {
            this.reader = reader;
        }

        @Override
        public void run() {
            CharBuffer buffer = CharBuffer.allocate(1024);
            try {
                while (reader.read(buffer) != -1){
                    String message = new String(buffer.array());
                    System.out.println("接收到发送的消息：" + message);
                    buffer = CharBuffer.allocate(1024);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
